package com.shwread.android.newui.page;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.NewActionHelp;
import com.TrainActionHelp;
import com.google.gson.reflect.TypeToken;
import com.shwread.android.newui.activity.BookListWebActivity;
import com.shwread.android.newui.activity.EvaluateWebActivity;
import com.shwread.android.newui.activity.NewResCheckActivity;
import com.shwread.android.newui.adapter.MyWorldPageAdapter;
import com.shwread.android.newui.adapter.SmartRecyclerAdapter;
import com.shwread.android.newui.tools.FullyGridLayoutManager;
import com.shwread.android.newui.view.AutoVerticalScrollTextView;
import com.shwread.android.qysw.activity.MainActivity;
import com.shwread.android.qysw.activity.MessageActivity;
import com.shwread.android.qysw.activity.psychological.EvaluatingHomeActivity;
import com.shwread.android.qysw10000229.R;
import com.shwread.android.ui.customview.BannerOnClickListener;
import com.shwread.android.ui.customview.QYViewPager;
import com.shwread.android.ui.customview.ViewPagerAdapter;
import com.shwread.android.ui.page.AbstractUIPage;
import com.shwread.android.ui.page.BoutiquePage;
import com.shwread.http.base.ObjectHttpResponseHandler;
import com.shwread.httpsdk.http.callback.BaseAction;
import com.shwread.httpsdk.http.face.QryMsgsByPositionAction;
import com.tgx.tina.android.ipc.framework.IUIPage;

import org.apache.http.Header;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import base.tina.core.task.infc.ITaskResult;
import logic.bean.BannerInfo;
import logic.bean.ColumnInfos;
import logic.bean.MessageBean;
import logic.bean.MessageInfo;
import logic.constants.DefaultConsts;

/**
 * Created by lex on 2017/7/8.
 */

public class MyWorldPage extends
        AbstractUIPage<MainActivity> {
    private static MyWorldPage instance;

    public static MyWorldPage getInstance(MainActivity t) {
        if (null == instance) {
            instance = new MyWorldPage(t);
        } else {
            instance.setActivity(t);
        }
        return instance;
    }

    public MyWorldPage(MainActivity t) {
        super(t);
    }

    private List<MessageInfo> messages;

    private TextView tvTitle;
    private ImageView ivPersion;
    private RecyclerView recyclerView;
    private String[] names = {"考勤管理", "家庭作业", "课程表", "学习计划", "考试倒计时", "成绩分析", "心理测评", "更多"};
    private Integer[] ids = {R.drawable.meiriqiandao,/* R.drawable.qingjia,*/ R.drawable.jiatingzuoye,
            R.drawable.kechengbiao, R.drawable.xinwen,
            R.drawable.daojishi, R.drawable.xueqingxinxi,
            R.drawable.ceping, R.drawable.gengduo};

    private MyWorldPageAdapter adapter;
    private AutoVerticalScrollTextView vtScrollText;
    private List<String> msgs = null;
    private LinearLayout llMessage;

    private int number = 0;
    private boolean isRunning = true;
    private boolean isLastSuccess = false;

    private QYViewPager vpPager;
    private ViewGroup vgPoints;
    private ViewPagerAdapter pagerAdapter;
    private HashMap<Integer, View> views;
    private List<BannerInfo> banners;
    private LinearLayout llVp;


    Runnable action = new Runnable() {
        @Override
        public void run() {
            int currentItem = vpPager.getCurrentItem();
            currentItem++;
            if (currentItem >= pagerAdapter.getCount()) {
                currentItem = 0;
            }
            vpPager.setCurrentItem(currentItem);
        }
    };

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 199) {
                vtScrollText.next();
                number++;
                if (msgs.size() != 0) {
                    vtScrollText.setText(msgs.get(number % msgs.size()));
                }
            }
        }
    };

    @Override
    public <E extends Activity> View createView(E arg0, int arg1) {
        if (null != curMyView) return curMyView;
        curMyView = bActivity.getLayoutInflater().inflate(R.layout.page_my_world, null);
        initView();
        return curMyView;
    }

    void initView() {
        msgs = new ArrayList<>();
        banners = new ArrayList<>();
        views = new HashMap<>();

        vpPager = (QYViewPager) curMyView.findViewById(R.id.my_world_head_pager);
        vgPoints = (ViewGroup) curMyView.findViewById(R.id.my_world_head_points);// banner下面的点
        llVp = (LinearLayout) curMyView.findViewById(R.id.llVp);
        LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) llVp.getLayoutParams();
        lp.height = DefaultConsts.BANNER_DEFAULT_HIGHT;
        lp.width = DefaultConsts.BANNER_DEFAULT_WIDTH;
        llVp.setLayoutParams(lp);

        vtScrollText = (AutoVerticalScrollTextView) curMyView.findViewById(R.id.vtScrollText);
        tvTitle = (TextView) curMyView.findViewById(R.id.common_header_name);
        tvTitle.setText(bActivity.getResources().getString(R.string.main_tab_str3));
        ivPersion = (ImageView) curMyView.findViewById(R.id.common_header_persion);
        llMessage = (LinearLayout) curMyView.findViewById(R.id.llMessage);
        ivPersion.setVisibility(View.VISIBLE);
        ivPersion.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                bActivity.goPersonalActivity();
            }
        });
        recyclerView = (RecyclerView) curMyView.findViewById(R.id.recyclerView);
        FullyGridLayoutManager gridLayoutManager = new FullyGridLayoutManager(bActivity, 4);
        recyclerView.setNestedScrollingEnabled(false);
        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(gridLayoutManager);
        adapter = new MyWorldPageAdapter(bActivity, names, ids);
        SmartRecyclerAdapter smartRecyclerAdapter = new SmartRecyclerAdapter(adapter);
        adapter.setOnRecyclerViewItemClickListener(new MyWorldPageAdapter.OnRecyclerViewItemClickListener() {
            @Override
            public void onItemClick(View view, Object data) {
                if (data.toString().equals("考勤管理")) {
                    Intent intent = new Intent(bActivity, NewResCheckActivity.class);
                    intent.putExtra("title", "考勤管理");
                    bActivity.startActivity(intent);
                } else if (data.toString().equals("心理测评")) {
                    Intent intent = new Intent(bActivity, EvaluatingHomeActivity.class);
                    intent.putExtra("title", "心理测评");
                    bActivity.startActivity(intent);
                } else {
                    bActivity.changePage(LoginViewPage.getInstance(bActivity), DEFAULT_STATUS);
                }
            }
        });
        recyclerView.setAdapter(smartRecyclerAdapter);
        vtScrollText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                bActivity.startActivity(new Intent(bActivity, MessageActivity.class));
            }
        });


        vpPager.setOnPageChangeListener(new PagerChangeListener());
        pagerAdapter = new ViewPagerAdapter(bActivity, views, new BannerClick());
        vpPager.setAdapter(pagerAdapter);

//        NewActionHelp.qryAutoServiceBanners(bActivity,10,);

        TrainActionHelp.qryBannerListByPosition(bActivity, 7, new QryBannerListByPositionHandler());
    }

    @Override
    public int enter(IUIPage<?> arg0) {
        if (!isLastSuccess) {
//            NewActionHelp.qryMsgsByPosition(bActivity, DefaultConsts.TYPE_POSITION_MESSAGECENTER, DefaultConsts.TYPE_WRITESOURCE_ALL, 1, 2000, new QryMsgsByPositionHandler());
            new QryMsgsByPositionAction(bActivity, DefaultConsts.TYPE_POSITION_MESSAGECENTER, DefaultConsts.TYPE_WRITESOURCE_ALL, 1, 2000, new GetMsgAction()).start();
        }
        return 0;
    }

    @Override
    public int leave(IUIPage<?> arg0) {
        isRunning = false;
        return 0;
    }

    @Override
    public void notifyView(int arg0, Bundle arg1) {

    }

    @Override
    public void setStatus(int arg0) {

    }

    @Override
    public View updateView(int arg0, ITaskResult arg1) {
        return null;
    }

    public static void destroy() {
        if (instance != null) {
            instance.dispose();
            instance = null;
        }
    }

    @Override
    public void dispose() {
        super.dispose();
    }

    private class GetMsgAction
            extends
            BaseAction {

        @Override
        protected void onError() {
            Log.e("加载失败了", "消息加载失败");
            isLastSuccess = false;
            super.onError();
        }

        @Override
        public void OK(Object obj) {
            isLastSuccess = true;
            final MessageBean msg = (MessageBean) obj;
            messages = msg.getColumns();
            if (messages == null || messages.size() == 0) {
                bActivity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        llMessage.setVisibility(View.GONE);
                    }
                });
                return;
            } else {
                for (int i = 0; i < messages.size(); i++) {
                    msgs.add(messages.get(i).getTitle());
                }
                bActivity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        vtScrollText.setText(msgs.get(0));
                    }
                });
                while (isRunning) {
                    SystemClock.sleep(3000);
                    handler.sendEmptyMessage(199);
                }
            }
        }
    }


    /**
     * Banner点击事件
     */
    private class BannerClick implements BannerOnClickListener {
        @Override
        public void click(BannerInfo info) {
            clickBanner(info);
        }
    }

    /**
     * Banner的滚动事件
     */
    private class PagerChangeListener implements ViewPager.OnPageChangeListener {
        @Override
        public void onPageScrollStateChanged(int state) {
        }

        @Override
        public void onPageScrolled(int arg0, float arg1, int arg2) {
        }

        @Override
        public void onPageSelected(int i) {
            int pageIndex = i;
            if (i == 0) {
                // 当视图在第一个时，将页面号设置为图片的最后一张。
                pageIndex = banners.size() - 2;
            } else if (i == banners.size() - 1) {
                // 当视图在最后一个是,将页面号设置为图片的第一张。
                pageIndex = 1;
            }
            if (i != pageIndex) {
                vpPager.setCurrentItem(pageIndex, false);
            }
            setViewPoint();
            startScroll();
        }
    }


    private void initBannerView() {
        if (banners.size() == 0) {
            return;
        }
        vgPoints.removeAllViews();
        for (int i = 0; i < banners.size() - 2; i++) {
            View view = bActivity.getLayoutInflater().inflate(R.layout.banner_grid_item, null);
            vgPoints.addView(view);
        }
        vpPager.setCurrentItem(1);
        setViewPoint();
        // pagerAdapter.setData(banners);
        pagerAdapter.notifyDataSetChanged();
        startScroll();
    }

    private void setViewPoint() {
        for (int i = 0; i < vgPoints.getChildCount(); i++) {
            View view = vgPoints.getChildAt(i);
            ImageView img = (ImageView) view.findViewById(R.id.banner_grid_item_image);

            if (i == vpPager.getCurrentItem() - 1) {
                img.setBackgroundResource(R.drawable.banner_grid_cur);
            } else {
                img.setBackgroundResource(R.drawable.banner_grid);
            }
        }
    }

    private void startScroll() {
        if (banners.size() <= 1) {
            return;
        }
        vpPager.removeCallbacks(action);
        vpPager.postDelayed(action, DefaultConsts.BANNER_CHANGE_TIME);
    }

    void clickBanner(BannerInfo info) {
        switch (info.getType()) {
            case BannerInfo.TYPE_BANNER:
                break;
            case BannerInfo.TYPE_BOOKS:
                break;
            case BannerInfo.TYPE_BOOKSURL:
                bActivity.goBookDetailActivity(info.getBooks());
                break;
            case BannerInfo.TYPE_URL:
            case BannerInfo.TYPE_INFORMATION:
//                bActivity.goWebViewActivity(info);
                Intent webIntent = new Intent(bActivity, BookListWebActivity.class);
                webIntent.putExtra(DefaultConsts.title_s, info.getBannerName());
                webIntent.putExtra(DefaultConsts.req_url_s, info.getContent());
                webIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
                bActivity.startActivity(webIntent);
                break;
        }
    }


    public class QryBannerListByPositionHandler extends
            ObjectHttpResponseHandler<List<BannerInfo>> {

        @Override
        public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
//            updateLoadingView(-1);
            isLastSuccess = false;

        }

        @Override
        public void onSuccess(int statusCode, Header[] headers, List<BannerInfo> object, String responseString) {
            banners.clear();
            if (object.size() <= 1) {
                banners = object;
            } else {
                banners.add(object.get(object.size() - 1));
                banners.addAll(object);
                banners.add(object.get(0));
            }
            System.out.println("企业专区banner obj:" + banners.toString());
            if (banners.size() > 0) {
                pagerAdapter.setData(banners);
                initBannerView();
            }
//            updateLoadingView(1);
//            gotoTop();
        }

        @Override
        public Type getType() {
            return new TypeToken<List<BannerInfo>>() {
            }.getType();
        }
    }

//    public class QryMsgsByPositionHandler
//            extends
//            ObjectHttpResponseHandler<com.shwread.android.newui.bean.Message> {
//        @Override
//        public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
//            isLastSuccess = false;
//            Log.e("QryMsgsByPosition",responseString.toString());
//        }
//
//        @Override
//        public void onSuccess(int statusCode, Header[] headers, com.shwread.android.newui.bean.Message object, String responseString) {
//            Log.e("QryMsgsByPosition",object.toString());
//            isLastSuccess = true;
//            final com.shwread.android.newui.bean.Message msg = object;
//            messages = msg.getMsgsViewsList();
//            if (messages == null || messages.size() == 0) {
//                llMessage.setVisibility(View.GONE);
//                return;
//            } else {
//                for (int i = 0; i < messages.size(); i++) {
//                    msgs.add(messages.get(i).getTitle());
//                }
//                vtScrollText.setText(msgs.get(0));
//                while (isRunning) {
//                    SystemClock.sleep(3000);
//                    handler.sendEmptyMessage(199);
//                }
//            }
//        }
//
//        @Override
//        public Type getType() {
//            return new TypeToken<com.shwread.android.newui.bean.Message>() {
//            }.getType();
//        }


}